package com.ruoyi.system.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.system.constant.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ImageToPdfConverter {

    public static void main(String[] args){
        List<Integer> pagelist = new ArrayList<>();
        Long scrid = 13l;
        pagelist.add(54761);
        pagelist.add(54762);
        pagelist.add(54763);
        pagelist.add(54764);
        pagelist.add(54765);
        pagelist.add(54766);
        pagelist.add(54767);
        pagelist.add(54768);
        generatePDF(pagelist,scrid,1);

    }



    public static void generatePDF(List<Integer> pagelist,Long scrid,int type){
        List<String> imagePaths = new ArrayList<>();
        for (Integer pageid:pagelist){
            String imagepath = Constants.BASE_DIR+scrid+ File.separator+"base_"+scrid+"_"+pageid+".png";
            imagePaths.add(imagepath);
        }
        try {
            if(type==1)
                convertImagesToPdf(imagePaths, Constants.BASE_DIR+scrid+File.separator+scrid+".pdf");
            else
                convertImagesToPdf(imagePaths, Constants.BASE_DIR+scrid+File.separator+scrid+"_v2.pdf");
            System.out.println("PDF created successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private static void convertImagesToPdf(List<String> imagePaths, String pdfOutputPath) throws IOException {
        Document document = new Document();

        try {
            PdfWriter.getInstance(document, new FileOutputStream(pdfOutputPath));
            document.open();

            for (String imagePath : imagePaths) {
                Image image = Image.getInstance(imagePath);
                // You can adjust image scale and position as needed
                Rectangle customPageSize = new Rectangle(500, 750);
                image.scaleToFit(customPageSize.getWidth(), customPageSize.getHeight());
                document.add(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}
